package by.msokoloff.javaweb2015.webapp.page;

import org.apache.wicket.Application;
import org.apache.wicket.authroles.authentication.AuthenticatedWebSession;
import org.apache.wicket.markup.html.WebPage;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.PasswordTextField;
import org.apache.wicket.markup.html.form.RequiredTextField;
import org.apache.wicket.markup.html.link.Link;
import org.apache.wicket.markup.html.panel.FeedbackPanel;
import org.apache.wicket.model.CompoundPropertyModel;
import org.apache.wicket.model.ResourceModel;
import org.apache.wicket.util.string.Strings;

public class LoginPage extends WebPage {

	private String username;
	private String password;

	@Override
	protected void onInitialize() {
		super.onInitialize();

		if (AuthenticatedWebSession.get().isSignedIn()) {
			setResponsePage(Application.get().getHomePage());
		}

		Form<Void> loginForm = new Form<Void>("loginForm") {
			@Override
			protected void onSubmit() {
				if (Strings.isEmpty(username) || Strings.isEmpty(password)) {
					return;
				}
				boolean authResult = AuthenticatedWebSession.get().signIn(username, password);
				if (authResult) {
					setResponsePage(AdminHomePage.class);
				} else {
					error("Ошибка авторизации");
				}
			}
		};

		loginForm.setDefaultModel(new CompoundPropertyModel<LoginPage>(this));
		loginForm.add(new RequiredTextField<String>("username"));
		loginForm.add(new PasswordTextField("password"));
		loginForm.add(new Link<Void>("gohome") {
			@Override
			public void onClick() {
				setResponsePage(HomePage.class);

			}
		});
		loginForm.add(new FeedbackPanel("feedback"));
		add(loginForm);
		
		add(new Label("pagetitle", new ResourceModel("p.loginPageTitle")));
	}

}
